package com.devshephard.juchm.threadPool;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * 延时执行线程池
 */
public class TestScheduledThreadPool {
    public static void main(String[] args) {

        ScheduledExecutorService pool = Executors.newScheduledThreadPool(2);

        //延时执行任务,多任务执行不会因为时间串行化而导致等待
        pool.schedule(()->{
            try {
                //这里等待十秒不会影响task2的运行
                TimeUnit.SECONDS.sleep(10);
                System.out.println(("task1"));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        },2, TimeUnit.SECONDS); //delay设定了该任务2秒后执行

        pool.schedule(()->{
            System.out.println(("task2"));
        },2, TimeUnit.SECONDS);


        //按照规定时间反复执行任务
        pool.scheduleAtFixedRate(()->{
            System.out.println("running");
        },1,1,TimeUnit.SECONDS); //延时一秒,间隔时间,时间单位
    }

}
